package com.zt.proxy.controller;

import java.util.List;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.zt.proxy.dto.PomDTO;
import com.zt.proxy.dto.ResultDTO;
import com.zt.proxy.exception.ServiceException;
import com.zt.proxy.model.PomModel;
import com.zt.proxy.service.PomService;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/proxy/pom")
@Slf4j
public class PomController {
    
    @Autowired
    private PomService pomService;

    @RequestMapping("/listDependencies")
    public String doListJars(PomDTO dto) {

        log.info("PomController.listDependencies({})", JSON.toJSONString(dto));

        String result;

        try {

            List<PomModel> models = pomService.listDependencies(dto);
            result = JSON.toJSONString(models);

        } catch(Exception e) {
            log.error("Exception {}", e);
            result = "[]";
        }

        return result;
    }
    
    /**
     * parse the upload content to pom model and fork another process to download the jars at background.
     *
     * @param pom
     * @return
     */
    @RequestMapping("/doParse")
    public ResultDTO<PomDTO> doParse(String pom) {

        ResultDTO<PomDTO> resultDTO;

        try {

            if (StringUtils.isEmpty(pom)) {
                throw new ServiceException("the pom content can't be blank.");
            }

            PomDTO dto = new PomDTO();
            dto.setPom(StringEscapeUtils.unescapeHtml4(pom));

            resultDTO = pomService.invoke(dto);

        } catch(Exception e) {

            resultDTO = ResultDTO.createExceptionResult(e, PomDTO.class);
        }

        return resultDTO;

    }
    
    @RequestMapping("/doLoad")
    public ResultDTO<String> doLoad() {

        log.info("PomController.doLoad");

        ResultDTO<String> resultDTO = null;

        try {

            resultDTO = pomService.loadJars("");

        } catch(Exception e) {

            resultDTO = ResultDTO.createExceptionResult(e, String.class);
        }

        return resultDTO;

    }

}
